from django.shortcuts import render
from django.http import HttpResponse
from .models import Author, Publisher, Book, Order
from django.db import models, connection


def index(request):
    result = Book.objects.aggregate(avg=models.Avg("price"))
    print(result)
    return HttpResponse(result["avg"])


def index2(request):
    result = Book.objects.annotate(avg=models.Avg("order__price"))
    print(result)
    return HttpResponse("je")


def index3(request):
    # result = Book.objects.aggregate(count=models.Count("id"))
    result = Book.objects.annotate(count=models.Count('order__id'))
    print(result)
    return HttpResponse("je")


def index4(request):
    result = Book.objects.annotate(max=models.Max("order__price"), min=models.Min("order__price"))
    for i in result:
        print("%s/%s/%s" % (i.name, i.max, i.min))
    return HttpResponse("w")


def index5(request):
    book = Book.objects.get(pk=1)
    print(book.name)
    return HttpResponse("w")


def index6(request):
    publisher = Publisher.objects.create(name="人民出版社")
    return HttpResponse("w")


def index7(request):
    order = Order.objects.count()
    print(order)
    return HttpResponse("w")


def index8(request):
    book = Book.objects.filter(order__price__gte=30).distinct()
    print(book.query)
    print(connection.queries)
    return HttpResponse("w")